﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Globalization;
using System.IO;

namespace SEOSitemap
{
    public class Helper
    {
        public static string ToW3CDateTime(DateTime dt)
        {
            string timeZone;

            if (dt.Kind == DateTimeKind.Utc)
            {
                timeZone = "Z";
            }
            else
            {
                TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(dt);

                if (offset.Ticks < 0)
                {
                    offset = -offset;
                    timeZone = "-";
                }
                else
                {
                    timeZone = "+";
                }

                timeZone += offset.Hours.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');
                timeZone += ":";
                timeZone += offset.Minutes.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');
            }

            return dt.ToString("yyyy-MM-ddTHH:mm" + timeZone, CultureInfo.InvariantCulture);
        }

        public static string ToXml(object obj)
        {
            using (StringWriter output = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture))
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9");
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(output, obj, ns);
                
                return output.ToString().Replace("utf-16", "utf-8");
            }
        }
    }
}
